// pages/sales/boss_ai/ai_detail.js
import * as echarts from '../ec-canvas/echarts';
var cf = require("../../../config.js");
var util = require("../../../utils/util.js");
var cusmallToken = wx.getStorageSync('cusmallToken');
var baseHandle = require("../../template/baseHandle.js");
var app = getApp();
Page(Object.assign({}, baseHandle, {

  /**
   * 页面的初始数据
   */
  data: {
    extConfig: wx.getExtConfigSync ? wx.getExtConfigSync() : {},
    app: app,
    staticResPath: cf.config.staticResPath,
    userImagePath: cf.config.userImagePath,
    activeTab: "radar",
    inAction: 1,
    hdTypeListShow: false,
    hdTypeActive: "1",
    hdTypeActiveName: "互动跟进",
    list:[],
    isLoading: false,
    pageSize: 10,
    curPage: 1,
    isBottom: false,
    ecAi: {
      lazyLoad: true
    },
    abilityData:{},
    employee:{},


    ecInt: {
      // 将 lazyLoad 设为 true 后，需要手动初始化图表
      lazyLoad: true
      // onInit: tChartx
    },
    interestData: {},
    ecFunnel: {
      lazyLoad: true
    },
    ecDealData: {},
    pickNameDeal: "近7天",
    ecActive: {
      lazyLoad: true
    },
    ecActiveData: {

    },
    ecInteraction: {
      lazyLoad: true
    },
    ecInteractionData: {
      list: []
    },
    pickerArr: [
      {
        name: "近7天",
        key: "7",
      },
      {
        name: "近15天",
        key: "15",
      },
      {
        name: "近30天",
        key: "30",
      }
    ],
    pickerName: "近7天",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var ctx = this;
    ctx.setData({
      eId: options.eId || "",
    })
    app.getUserInfo(ctx, options, function (userInfo, res) {
      cusmallToken = wx.getStorageSync('cusmallToken');
      ctx.queryAbilityData(ctx.data.eId);
      ctx.deal(7);
      ctx.interest();
      ctx.active();
      ctx.interaction();
      

    });
    
  },
  toPoster(){
    wx.navigateTo({
      url: '/pages/canvas/canvas?eId=' + this.data.eId,
    })
  },
  changeTab(e){
    var tab = e.currentTarget.dataset.tab;
    var ctx = this;
    
    ctx.setData({
      activeTab:tab
    });
    if ("radar" == tab){
      ctx["radarComponent"] = ctx.selectComponent('#mychart-ai');
      ctx.initCommEc("radarComponent", "setRadarOption", ctx.data.abilityData);
    }else if ("dataAnalysis" == tab) {
      ctx.renderInter();
      ctx.renderActive();
      ctx.renderInteraction();
    }
  },
  queryAbilityData(eid) {// ai analysis --- ability, radar data
    var ctx = this;
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/dataprofile/abilityInfo",
      data: {
        cusmallToken: cusmallToken,
        eid: eid
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        if (data && 0 === data.ret) {
          
          ctx.setData({
            abilityData: data.model.abilityData,
            employee: data.model.employee,
            consultCount: data.model.consultCount,
            followCount: data.model.followCount,
            memberCount: data.model.memberCount,
            forwardCount: data.model.forwardCount,
            saveCount: data.model.saveCount,
            thumbsCount: data.model.thumbsCount,
            pv: data.model.pv,
          });
          
        } else {

        }
      },
      fail() {

      },
      complete() {
        ctx["radarComponent"] = ctx.selectComponent('#mychart-ai');
        ctx.initCommEc("radarComponent", "setRadarOption", ctx.data.abilityData);
      }
    });
  },
  initCommEc(domName, optionName, params) {
    let ctx = this;
    this[domName].init((canvas, width, height) => {
      // 获取组件的 canvas、width、height 后的回调函数
      // 在这里初始化图表
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      ctx[optionName](chart, params);

      // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
      this.chart = chart;

      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return chart;
    });
  },
  setRadarOption(chart, itemData) {
    let ctx = this;
    var option = {
      backgroundColor: "#fff",
      color: ["rgba(114, 172, 209,0.8)"],
      // tooltip: {},
      xAxis: {
        show: false
      },
      yAxis: {
        show: false
      },
      radar: {
        indicator: [{
          name: '获客能力值',
          max: 100
        },
        {
          name: '销售主动值',
          max: 100
        },
        {
          name: '官网推广值',
          max: 100
        },
        {
          name: '个人能力值',
          max: 100
        },
        {
          name: '客户互动值',
          max: 100
        },
        {
          name: '产品推广值',
          max: 100
        }
        ]
      },
      series: [{
        type: 'radar',
        data: [{
          value: [itemData.customerAbility,
          itemData.saleAbility,
          itemData.portalSpreadAbility,
          itemData.personalAbility,
          itemData.interactionAbility,
          itemData.productSpreadAbility

          ],
          areaStyle: {
            normal: {
              color: 'rgba(114, 172, 209, 0.7)'
            }
          }
        }
        ]
      }]
    };

    chart.setOption(option);
  },
  
  //成交 漏斗
  deal: function (day) {
    var ctx = this;

    var submitData = {
      cusmallToken: cusmallToken,
      countAll: false,
      eid: ctx.data.eId,
    }
    if (day) {
      submitData.startDate = util.formatDate(new Date(Date.now() - (day * 86400000)));
      submitData.endDate = util.formatDate(new Date(Date.now() - (1 * 86400000)));
    }
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/dataprofile/bargainFunnel",
      data: submitData,
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        if (data && 0 === data.ret) {
          ctx.setData({
            dealData: data.model
          });
          
        } else {

        }
      },
      fail() {

      },
      complete() {
      }
    });
  },
  bindPickerChange(e) {
    let ctx = this;
    let day = this.data.pickerArr[e.detail.value].key;
    let name = this.data.pickerArr[e.detail.value].name;
    let target = e.currentTarget.dataset.target;
    if ("dealper" == target) {
      ctx.deal(day);
      ctx.setData({
        pickNameDeal: name
      });
    }
  },
  interest() {//兴趣统计
    var ctx = this;
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/dataprofile/interest",
      data: {
        cusmallToken: cusmallToken,
        eid:ctx.data.eId,
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;

        if (data && 0 === data.ret) {
          ctx.setData({
            interestData: {
              toCompanyPerD: data.model.toCompanyPerD,
              toMePerD: data.model.toMePerD,
              toProductPerD: data.model.toProductPerD
            }
          })
        } else {
          ctx.setData({
            interestData: {
              toCompanyPerD: 33.33,
              toMePerD: 33.33,
              toProductPerD: 33.33
            }
          })
        }
      },
      fail() {

      },
      complete() {
       
      }
    });
  },
  renderInter(){
    var ctx = this;
    ctx["interestComponent"] = ctx.selectComponent('#mychart-dom-pie');
    ctx.initCommEc("interestComponent", "setInterestOption");
  },
  setInterestOption(chart) {
    let ctx = this;
    var option = {
      color: ["#FF5722", "#FF9800", "#00BCD4"],
      legend: {
        itemWidth: 10,
        itemHeight: 10,
        selectedMode: false,
        orient: 'horizontal',
        bottom: 40,
        data: ["对我感兴趣", "对产品感兴趣", "对公司感兴趣"]
      },
      series: [{
        label: {
          normal: {
            fontSize: 14,
            formatter: "{d}%",
            color: "#000000"
          }
        },
        type: 'pie',
        center: ['50%', '40%'],
        radius: [0, '60%'],
        data: [{
          value: ctx.data.interestData.toCompanyPerD,
          name: '对我感兴趣'
        }, {
          value: ctx.data.interestData.toMePerD,
          name: '对产品感兴趣'
        }, {
          value: ctx.data.interestData.toProductPerD,
          name: '对公司感兴趣'
        },
        ],

        itemStyle: {
          emphasis: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 2, 2, 0.3)'
          }
        }
      }]
    };
    chart.setOption(option);
  },
  //活跃度
  active: function () {
    var ctx = this;
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/dataprofile/activeTrend",
      data: {
        cusmallToken: cusmallToken,
        eid: ctx.data.eId,
        dayNum: 15
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        if (data && 0 === data.ret) {
          var activeNum = [];
          var activeDay = [];
          for (let item of data.model.list) {
            activeNum.push(item.activeNum);
            activeDay.push(item.day.substring(5));
          }
          ctx.setData({
            ecActiveData: {
              activeNum: activeNum.reverse(),
              activeDay: activeDay.reverse()
            }
          })
        }
      },
      fail() {

      },
      complete() {
        
      }
    });
  },
  renderActive() {
    var ctx = this;
    ctx["activeComponent"] = ctx.selectComponent('#mychart-dom-line');
    ctx.initCommEc("activeComponent", "setActiveOption");
  },
  setActiveOption(chart) {
    let ctx = this;
    var option = {
      title: {
        text: '',
        left: 'center'
      },
      color: ["#37A2DA"],

      grid: {
        containLabel: true
      },

      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: ctx.data.ecActiveData.activeDay,
      },
      yAxis: {
        x: 'center',
        type: 'value',
        splitLine: {
          lineStyle: {
            type: 'solid'
          }
        },
        min: 0
      },
      series: [{
        name: "活跃度",
        type: 'line',
        smooth: true,
        data: ctx.data.ecActiveData.activeNum
      }]
    };

    chart.setOption(option);

  },
  //互动统计
  interaction() {//客户互动数据
    var ctx = this;
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/dataprofile/interaction",
      data: {
        cusmallToken: cusmallToken,
        eid: ctx.data.eId,
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        if (data && 0 === data.ret) {
          ctx.setData({
            ecInteractionData: {
              list: [data.model.thumbs, data.model.addMemory, data.model.comment, data.model.askGoods, data.model.forward, data.model.call, data.model.save]
            }
          });
        }
      },
      fail() {

      },
      complete() {
        
      }
    });

  },
  renderInteraction() {
    var ctx = this;
    ctx["interactionComponent"] = ctx.selectComponent('#mychart-dom-bar');
    ctx.initCommEc("interactionComponent", "setInteractionOption");
  },
  setInteractionOption(chart) {
    let ctx = this;
    var option = {
      title: {
        text: '',
        left: 'center'
      },
      grid: {
        containLabel: true
      },

      xAxis: {
        type: 'value',
        axisLine: {
          lineStyle: {
            color: '#999'
          }
        },
        axisLabel: {
          color: '#666'
        }
      },
      yAxis:
        {
          type: 'category',
          axisTick: { show: false },
          data: ['点赞', '添加印象', '评论', '咨询产品', '转发', '拨打电话', '保存电话'],
          axisLine: {
            lineStyle: {
              color: '#999'
            }
          },
          axisLabel: {
            color: '#666'
          }
        }
      ,
      series: [{
        smooth: true,
        type: 'bar',
        label: {
          normal: {
            show: true,
            position: 'inside'
          }
        },
        data: ctx.data.ecInteractionData.list,
        itemStyle: {
          normal: {
            color: function (params) {
              var colorList = ["#FF5722", "#FF9800", "#00BCD4", "#9E9E9E", "#616161", "#795548", "#009688"];
              return colorList[params.dataIndex];
            }
          }
        }
      }]
    };

    chart.setOption(option);
  },
  closeSome: function (e) {
    if ("hdtype" != e.target.dataset.tab) {

      this.setData({
        hdTypeListShow: false
      });
    }

  },
  extendHd(e) {
    var ctx = this;
    // ctx.setData({
    //   hdTypeListShow: !ctx.data.hdTypeListShow
    // });

    ctx.setData({
      list: [],
      curPage: 1,
      isBottom: false,
      activeTab: "interaction",
    });
    ctx.queryBehaviorTrail();
  },
  hdFetchList(e) {
    var ctx = this;
    var hdType = e.currentTarget.dataset.hdtype;
    var hdTypeActiveName = "";
    switch (hdType) {
      case "1":
        hdTypeActiveName = "互动跟进";
        break;
      case "2":
        hdTypeActiveName = "雷达互动";
        break;
      case "3":
        hdTypeActiveName = "跟进记录";
        break;
    }
    ctx.setData({
      hdTypeActiveName: hdTypeActiveName,
      hdTypeActive: hdType,
      inAction: parseInt(hdType),
      list: [],
      curPage: 1,
      isBottom: false,
      activeTab: "interaction"
    });
    ctx.queryBehaviorTrail();
  },
  queryBehaviorTrail(cb) {
    var ctx = this;
    if (ctx.data.isLoading || ctx.data.isBottom) {
      return;
    }
    ctx.setData({ isLoading: true });
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/bahavior/queryBehaviorTrail",
      data: {
        cusmallToken: cusmallToken,
        eid: ctx.data.eId,
        start: (ctx.data.curPage - 1) * ctx.data.pageSize,
        limit: ctx.data.pageSize
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        if (data && 0 === data.ret) {
          var list = data.model.list;
          for (let item of list) {
            item.behaviorTxt = util.behaviorType(item.type, item.count);
            item.behaviorTime = util.timestampToDayHkt(item.createTime);
            if (item.sttr1 && item.sttr1.length > 10) {
              item.sttr1 = item.sttr1.substring(0, 6) + "...";
            }
          }
          ctx.setData({
            list: ctx.data.list.concat(list),
          });
          if (data.model.total == ctx.data.list.length) {
            ctx.setData({
              isBottom: true
            });
          }
        } else {

        }
        cb && cb();
      },
      fail() {

      },
      complete() {
        ctx.setData({ isLoading: false });
      }
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var ctx = this;
    if (!ctx.data.isLoading || "interaction" == ctx.data.tab) {
      ctx.setData({ curPage: ctx.data.curPage + 1 });
      ctx.queryBehaviorTrail();
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
}))